import PetModel from '../../model/petModel/petModel.js';
import { GetConnection, GetResult } from "../../util/db.js";
import { JoinSQLInsertKeys } from "../../util/JoinSQL.js";

class PetService {
    /**
     * @param {string} ownerID 
     */
    static async GetOnlyOwner(ownerID) {
        try {
            const conn = await GetConnection()
            let sql = `
SELECT a.*,b.breedName,c.portraitSrc as user_portraitSrc
FROM pet a
LEFT JOIN breed b on a.breedID =  b.id
LEFT JOIN usertable c on a.ownerID = c.id
WHERE a.ownerID = ?
`;
            const { rows: result } = await GetResult(sql, [ownerID], conn)
            return result
        } catch (error) {
            return Promise.reject(error)
        }
    }
    /**
     * @param {any} condition 
     */
    static async InsertPet(condition) {
        try {
            const model = new PetModel(condition)
            const conn = await GetConnection()
            let sql = "insert into pet"
            let { keys, values } = model.GetKeys_Values()
            sql += JoinSQLInsertKeys(keys)
            const { rows: result } = await GetResult(sql, [[values]], conn, true)
            return result
        } catch (error) {
            return Promise.reject(error)
        }
    }
    /**
     * @param {Array<>} modelArray 
     */
    static async InsertPetList(modelArray) {
        try {
            let valuesArray = []
            for (const item of modelArray) {
                valuesArray.push(new PetModel(item).GetKeys_Values().values)
            }
            const model = new PetModel(modelArray[0])
            const conn = await GetConnection()
            let sql = "insert into pet"
            sql += JoinSQLInsertKeys(model.GetKeys_Values().keys)
            const { rows: result } = await GetResult(sql, [valuesArray], conn, true)
            return result && result.affectedRows
        } catch (error) {
            return Promise.reject(error)
        }
    }

    /**
     * @param {PetModel} model
     */
    static async DeletePet(model) {
        try {
            model = new PetModel(model)
            let conn = await GetConnection()
            let sql = "delete from pet where id = ?"
            let { rows } = await GetResult(sql, [model.id], conn, true)
            return rows && rows.affectedRows
        } catch (error) {
            return Promise.reject(error)
        }
    }
}

export default PetService;